package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.LogDTO;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IPUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.system.entity.SysOperationLog;
import org.jeecg.modules.system.mapper.SysOperationLogMapper;
import org.jeecg.modules.system.service.ISysOperationLogService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 操作日记
 * @Author: jeecg-boot
 * @Date:   2020-09-22
 * @Version: V1.0
 */
@Service
public class SysOperationLogServiceImpl extends ServiceImpl<SysOperationLogMapper, SysOperationLog> implements ISysOperationLogService {

	@Autowired
	private SysOperationLogMapper sysOperationLogMapper;
	
	@Override
	@Transactional
	public void saveMain(SysOperationLog sysOperationLog ) {
		sysOperationLogMapper.insert(sysOperationLog);
	}

	@Override
	@Transactional
	public void updateMain(SysOperationLog sysOperationLog) {
		sysOperationLogMapper.updateById(sysOperationLog);
		
		//1.先删除子表数据
		
		//2.子表数据重新插入
	}

	@Override
	@Transactional
	public void delMain(String id) {
		sysOperationLogMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			sysOperationLogMapper.deleteById(id);
		}
	}



	@Override
	public void addLog(String logContent,Integer logType, Integer operatetype, LoginUser user) {
		System.err.println(logContent+logType+operatetype+user);
		SysOperationLog sysLog = new SysOperationLog();
		sysLog.setId(String.valueOf(IdWorker.getId()));
		//注解上的描述,操作日志内容
		sysLog.setOperationContent(logContent);
		sysLog.setLogType(logType);
		sysLog.setOperateType(operatetype);
		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//设置IP地址
			sysLog.setIp(IPUtils.getIpAddr(request));
		} catch (Exception e) {
			sysLog.setIp("127.0.0.1");
		}
		//获取登录用户信息
		if(user==null){
			try {
				user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			} catch (Exception e) {
				//e.printStackTrace();
			}
		}
		if(user!=null){
			sysLog.setUserid(user.getUsername());
			sysLog.setUsername(user.getRealname());
		}
		sysLog.setCreateTime(new Date());
		//保存系统日志
		baseMapper.insert(sysLog);
		System.err.println(sysLog);
	}
	
}
